package com.lyf.controller;

import com.lyf.comon.ResponseResult;
import com.lyf.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@CrossOrigin
@RestController
@RequestMapping("/file")
@Slf4j
public class FileUploadController {
    @Autowired
    private AliOssUtil aliOssUtil;

    @PostMapping("/upload")
    public ResponseResult uploadFile(@RequestParam(value = "file",required = false) MultipartFile file){
        // 判断文件是否为空
        if(file.isEmpty()){
            return ResponseResult.fail();
        }

        try {
            //原始文件名
            String originalFilename = file.getOriginalFilename();
            //截取原始文件名的后缀   dfdfdf.png
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            //构造新文件名称
            String objectName = UUID.randomUUID().toString() + extension;

            //文件的请求路径
            String filePath = aliOssUtil.upload(file.getBytes(), objectName);
            return new ResponseResult(200, "文件上传成功", filePath);
        } catch (IOException e) {
            log.error("文件上传失败：{}", e);
        }

        return ResponseResult.fail();

    }

    @PostMapping("/uploadUser")
    public ResponseResult uploadFileUser(@RequestParam(value = "file",required = false) MultipartFile file){
        // 判断文件是否为空
        if(file.isEmpty()){
            return ResponseResult.fail();
        }

        try {
            //原始文件名
            String originalFilename = file.getOriginalFilename();
            //截取原始文件名的后缀   dfdfdf.png
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            //构造新文件名称
            String objectName = UUID.randomUUID().toString() + extension;

            //文件的请求路径
            String filePath = aliOssUtil.upload(file.getBytes(), objectName);
            return new ResponseResult(200, "文件上传成功", filePath);
        } catch (IOException e) {
            log.error("文件上传失败：{}", e);
        }

        return ResponseResult.fail();
    }
}




